<template>
	<el-dialog
		title="管理角色权限"
		v-model="state.visible"
		width="400px"
	>
    <el-checkbox-group v-model="state.choiceIds" style="display: flex;flex-direction: column;">
        <div v-for="item in state.ruleForm" style="display: flex;flex-direction: row;justify-content: space-around;align-items: center;margin-bottom: 10px;">
          <el-checkbox  :label="item.permissionName" :value="item.permissionId" />
          <a style="font-size: 12px;">{{ state.preList.includes(item.permissionId) ? '已选择' : '' }}</a>
        </div>
    </el-checkbox-group>
		<template #footer>
			<span class="dialog-footer">
			  <el-button @click="close">取 消</el-button>
			  <el-button type="primary" @click="submitForm">确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup>
import {reactive, ref} from 'vue';
import {rolePermissionUpdate} from '@/api/role';
import {permissionByRoleId, getAllPermissions} from '@/api/permission';
import {localGet} from '@/utils';
import {ElMessage} from 'element-plus';
import md5 from 'js-md5';


const state = reactive({
  token: localGet('token') || '',
  visible: false,
  ruleForm: {},
  roleId: '',
  choiceIds: [],
  preList: [],
  rules: {
    roleName: [
      {required: 'true', message: '角色名不能为空', trigger: ['change']}
    ]
  },
  id: ''
});
// 获取详情
const getDetail = async (id) => {
  console.log('详情', id);
  await getAllPermissions().then(res => {
    state.ruleForm = res.data.data;
    console.log('当前数据', state.ruleForm);
  });
  await permissionByRoleId({roleId: id}).then(res => {
    console.log('当前角色权限详情', res.data.data);
    state.preList = res.data.data;
  });
};
// 开启弹窗
const open = (row) => {
  state.visible = true;
  console.log('当前行', row);
  if (row) {
    console.log('载入行数据，{}', row);
    state.roleId = row.roleId
    getDetail(row.roleId);
  } else {
    state.ruleForm = {};
  }
};
// 关闭弹窗
const close = () => {
  state.visible = false;
  // 清除数据
  state.ruleForm = {};
  state.choiceIds = [];
  state.preList = [];
  state.id = '';
};

const submitForm = async () => {
  console.log("当前角id",state.roleId);
  console.log("当前角id",state.choiceIds)
  if (state.choiceIds.length === 0){
    ElMessage.warning('请选择权限');
    return
  }
  await rolePermissionUpdate({
    roleId: state.roleId,
    permissionIds: state.choiceIds
  }).then((res) => {
    console.log('修改权限结果', res)
    ElMessage.success(res.data.data)
  }).catch((err) => {
    console.log('修改权限失败', err)
    ElMessage.error('修改权限失败');
  })

  close();

};
defineExpose({open, close});
</script>

<style scoped>
.avatar-uploader {
    width: 100px;
    height: 100px;
    color: #ddd;
    font-size: 30px;
}

.avatar-uploader >>> .el-upload {
    width: 100%;
    text-align: center;
}

.avatar-uploader-icon {
    display: block;
    width: 100%;
    height: 100%;
    border: 1px solid #e9e9e9;
    padding: 32px 17px;
}
</style>
